package org.springframework.ai.mcp.server.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 简单SSE控制器
 * 
 * <p>提供基础的SSE端点以支持MCP客户端连接。
 * 这是一个临时解决方案，用于解决客户端连接404问题。
 */
@RestController
@RequestMapping
public class SseController {

    private static final Logger logger = LoggerFactory.getLogger(SseController.class);
    
    private final ConcurrentMap<String, SseEmitter> clients = new ConcurrentHashMap<>();

    /**
     * SSE端点 - 匹配MCP客户端期望的路径
     */
    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sse(@RequestParam(value = "clientId", defaultValue = "default") String clientId) {
        logger.info("🔗 新SSE连接: clientId={}", clientId);
        
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); // 无超时
        clients.put(clientId, emitter);
        
        // 发送初始事件
        try {
            emitter.send(SseEmitter.event()
                .name("connect")
                .data("SSE连接已建立 - clientId: " + clientId));
                
            emitter.send(SseEmitter.event()
                .name("mcp-ready")
                .data("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\",\"params\":{}}"));
        } catch (IOException e) {
            logger.error("发送初始SSE事件失败: {}", e.getMessage());
            clients.remove(clientId);
            emitter.complete();
        }
        
        // 设置完成和错误处理
        emitter.onCompletion(() -> {
            logger.info("🔌 SSE连接关闭: clientId={}", clientId);
            clients.remove(clientId);
        });
        
        emitter.onError((ex) -> {
            logger.error("❌ SSE连接错误: clientId={}, error={}", clientId, ex.getMessage());
            clients.remove(clientId);
        });
        
        emitter.onTimeout(() -> {
            logger.warn("⏰ SSE连接超时: clientId={}", clientId);
            clients.remove(clientId);
        });
        
        return emitter;
    }
    
    /**
     * MCP消息端点
     */
    @PostMapping(value = "/mcp/message", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void mcpMessage(@RequestBody String message, 
                          @RequestParam(value = "clientId", defaultValue = "default") String clientId) {
        logger.info("📨 收到MCP消息: clientId={}, message={}", clientId, message);
        
        // 简单的响应逻辑
        SseEmitter emitter = clients.get(clientId);
        if (emitter != null) {
            try {
                emitter.send(SseEmitter.event()
                    .name("mcp-response")
                    .data("{\"jsonrpc\":\"2.0\",\"result\":{\"capabilities\":{\"tools\":{}}}}"));
            } catch (IOException e) {
                logger.error("发送MCP响应失败: {}", e.getMessage());
                clients.remove(clientId);
            }
        } else {
            logger.warn("⚠️ 找不到客户端: clientId={}", clientId);
        }
    }
    
    /**
     * 获取连接状态
     */
    @GetMapping("/sse/status")
    @ResponseBody
    public String sseStatus() {
        return String.format("SSE服务器运行中 - 当前连接数: %d", clients.size());
    }
} 
